/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <sys/time.h>
#include "log.h"

tLogLevel g_logthreshold;

static char* g_filename = NULL;

void WISHMASTER_EXPORT setLogLevel(tLogLevel ll)
{
	g_logthreshold = ll;
}

void WISHMASTER_EXPORT log(tLogLevel ll, const char* format, ...)
{
	if(ll < g_logthreshold)
	{
		return;
	}
	char buf[LOGBUFFER_SIZE];
	va_list args;
	va_start(args, format);
	vsnprintf(buf, LOGBUFFER_SIZE, format, args);
	va_end(args);
	if(g_filename)
	{
		struct timeval tp;
		gettimeofday(&tp, NULL);
		FILE* fp = fopen(g_filename, "a");
		fprintf(fp,"%d:%d -> %s\n", (int)tp.tv_sec, (int)tp.tv_usec, buf);
		fclose(fp);
	}
	fprintf(stderr, "%s\n", buf);
}

void WISHMASTER_EXPORT setLogfile(const char* filename)
{
	if(g_filename)
		free(g_filename);
	int length = strlen(filename);
	g_filename = (char*)malloc(length + 1);
	strncpy(g_filename, filename, length);
	g_filename[length] = 0;
	FILE* fp = fopen(filename, "w+");
	if(!fp)
	{
		return; //error
	}
	fclose(fp);
}

